import request from '../uview-ui/libs/request'
import { config } from './index.js'

const uploadToken = function (fileBucket = 'image1') {
	return request.post('/common/uploads', {
		bucket: fileBucket
	}, {
		token: uni.getStorageSync('token')
	})
}

/*
todo:
	获取CDN文件服务器上传所需的token
params: 
	fileBucket => '远程资源服务器对应的储存桶名'
*/
export const getqnToken = async function (fileBucket = "image1") {
	let qntoken = await uploadToken(fileBucket);
	return qntoken.data.up_token
}

// 根据token获取用户userID，需要传入token
export const getUserId = function (token) {
	let reversal = token.split('').reverse().join('')
	let user_id = reversal.substr(1, reversal.indexOf('_') - 3).split('').reverse().join('')
	return user_id;
}

/**
 * todo:
	异步转同步文件队列上传，因为小程序无法多线程上传
params: 
	url => '上传路径',
	fileList => [{
		src: 文件本地路径
		name: 文件名
	}],
	progress =>{
		fileList[uploaded_index] = true
	},
	fileType: '文件类型，img , xls, dox'
 */
export const uploadFiles = async (fileList, progress, url = config.upLoadAction , fileType = 'img') => {
	const qntoken = await getqnToken()
	// uni.setStorageSync('qntoken', qntoken)
	let line_urls = []
	let maxLen = fileList.length - 1
	let curIdx = -1
	await Promise.all(fileList.map(async file => {
		if (file.src.includes(config.qnAssetsHost)) {
			return line_urls.push(file.src.replace(config.qnAssetsHost, ''))
		}
		let upData = {
			url: url,
			filePath: file.src,
			name: 'file',
			formData: {
				//正则匹配最后一个. ,给这个文件替换上时间戳，防止重名报错
				key: file.name.replace(/(.*\.)/, `${fileType}_${new Date().getTime()}.`),
				token: qntoken
			}
		}

		let res = await uni.uploadFile(upData)
		console.log(res)

		curIdx++
		if (progress && typeof progress == 'function') {
			progress(curIdx)
		}
		
		line_urls.push(JSON.parse(res[1].data).key)
	}))
	return line_urls
}

/**
 * 检查版本
 * 更新
 */
export const checkVersion = () => {
	const updateManager = uni.getUpdateManager();
	// 顺便存一个版本号
	const accountInfo = uni.getAccountInfoSync();
	uni.setStorageSync('nowVersion', accountInfo.miniProgram.version);

	updateManager.onCheckForUpdate(function (res) {
		//success
		console.log(res.hasUpdate);
	});

	updateManager.onUpdateReady(function (res) {
		uni.showModal({
			title: '更新提示',
			content: '新版本已经准备好，请更新并重启应用？',
			confirmColor: '#2979ff',
			showCancel: false,
			success: (res) => {
				if (res.confirm) {
					uni.clearStorageSync();
					// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
					updateManager.applyUpdate();
				}
			}
		});
	});

	updateManager.onUpdateFailed(function (res) {
		uni.showModal({
			title: '更新提示',
			content: '下载更新失败，请检查网络链接',
			confirmColor: '#2979ff'
		});
	});
}

/**
 * 获取版本号
 */
export async function getVersion() {
	const accountInfo = uni.getAccountInfoSync();
	let value = uni.getStorageSync('nowVersion') ? uni.getStorageSync('nowVersion') : '1.4.5';    // 上一版本号
	let oldversion = parseInt(value.replaceAll('.', ''))
	let newVersion = parseInt(accountInfo.miniProgram.version.replaceAll('.', ''))
	console.log(oldversion, newVersion)
	if (oldversion < newVersion) {
		checkVersion()
	}
	uni.setStorageSync('nowVersion', accountInfo.miniProgram.version);
}